﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.UI.WebControls;
using Koonsoft.HYCRM.BLL;
using Koonsoft.HYCRM.DAL;
using Koonsoft.HYCRM.Model;

public partial class Order_MakeOrder : BasePage
{
    private log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {


            // 判断是否存在缓存ID
            if (Request.QueryString["cacheId"] != null)
            {
                CacheID.Value = Request.QueryString["cacheId"];
                FillFormByObjectCache();
            }
            else
            {
                string cacheId = Guid.NewGuid().ToString();
                CacheID.Value = cacheId;
            }

            UserLoginName.Value = User.Identity.Name;
            UserRoleID.Value = new RoleBLL().GetRoleIDByLoginName(User.Identity.Name).ToString();

            if (!IsPostBack)
            {
                BindYearAuditList();
            }
        }
    }

    /// <summary>
    /// 下一步按钮按下时激发事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void PreBuildOrder_Click(object sender, EventArgs e)
    {
        string errormsg;

        var order = EncapsulationOrder();

        string str = XmlObjectHelper.ObjectToXML(order);

        var orderService = new OrderService();
        orderService.Url = ConfigurationManager.AppSettings["OrderServiceURL"];

        // 通过Web Services进行校验
        if (!orderService.OrderDataValidation(order, out errormsg))
        {
            ErrorMessage.Text = errormsg;
            ErrorMessage.Visible = true;
            return;
        }
        else
        {
            ErrorMessage.Visible = false;
        }

        // 处理缓存
        if (Request.QueryString["cacheId"] != null)
        {
            UpdateObjectToCache(order, Request.QueryString["cacheId"]);
        }
        else
        {
            // 将输入数据存入缓存
            AddObjectToCache(order);
        }

        // 页面跳转
        Response.Redirect("ConfirmOrder.aspx?cacheId=" + CacheID.Value);
    }

    /// <summary>
    /// 封装订单
    /// </summary>
    /// <returns></returns>
    private OrderInfo EncapsulationOrder()
    {
        try
        {
            var order = new OrderInfo
            {
                OrderID = string.Empty,
                EnglishCompanyName = EnglishName.Text.Trim(),
                ChineseCompanyName = ChineseName.Text.Trim(),
                RegisterRegionID = Convert.ToInt32(RegisterRegion.SelectedValue),
                RegisterStock = Convert.ToInt32(Stock.Text.Trim()),
                RegisiterDate = Convert.ToDateTime(RegisterDate.Text.Trim()),
                ClientName = ClientName.Text.Trim(),
                Telephone = Telephone.Text.Trim(),
                Mobile = Mobile.Text.Trim(),
                Address = Address.Text.Trim(),
                Email = Email.Text.Trim(),
                IM = IM.Text.Trim(),
                Fax = Fax.Text.Trim(),
                ClientType = (ClientType)Convert.ToInt32(ClientType.SelectedValue),
                OrderTime = DateTime.Now,
                Amount = Convert.ToInt32(Amount.Text.Trim()),
                CurrencyType = (CurrencyType)Convert.ToInt32(CurrencyType.SelectedValue),
                BranchID = Convert.ToInt32(Branch.SelectedValue),
                EmpolyeeID = Convert.ToInt32(Empolyee.SelectedValue),
                DelegateTypeID = Convert.ToInt32(DelegateType.SelectedValue),
                Remark = OrderRemark.Text.Trim(),
                IsSubsidiary = CheckBox1.Checked,
                ParentCompanyID = TextBox1.Text.Trim(),
                CompanyID = CompanyID.Text.Trim(),
                PaymentStatus = 0,
                AgentCompanyName = AgentCompany.Text.Trim(),
                AuditYear = Convert.ToInt32(AuditYear.SelectedValue)
            };

            if (DelegateType.SelectedValue == "5")
            {
                order.BR = txtBr.Text;
                order.BusinessAddress = txtBusinessAddress.Text;
                order.BusinessScope = txtBusinessScope.Text;
                order.EndTime = Convert.ToDateTime(txtEndTime.Text);
                order.StartTime = Convert.ToDateTime(txtStartTime.Text);
                order.TotalTurnover = Convert.ToInt32(txtTotalTurnover.Text);
                order.ProfitTax = Convert.ToInt32(txtProfitTax.Text);
            }

            return order;
        }
        catch (Exception ex)
        {
            logger.Error("报单信息异常", ex);
            ErrorMessage.Text = string.Format("报单信息异常，{0}", ex.Message);
        }

        return null;
    }

    /// <summary>
    /// 将报单对象存入缓存
    /// </summary>
    /// <param name="order"></param>
    private void AddObjectToCache(OrderInfo order)
    {
        try
        {
            ObjectCacheHelper.AddObjectCache(order, CacheID.Value);
        }
        catch (Exception ex)
        {
            var logger = log4net.LogManager.GetLogger("File");

            logger.Debug("报单信息存入缓存出错", ex);
        }
    }

    /// <summary>
    /// 更新报单对象缓存
    /// </summary>
    /// <param name="order"></param>
    /// <param name="cacheID"></param>
    private void UpdateObjectToCache(OrderInfo order, string cacheID)
    {
        try
        {
            ObjectCacheHelper.UpdateObjectCache(order, cacheID);
        }
        catch (Exception ex)
        {
            var logger = log4net.LogManager.GetLogger("File");

            logger.Debug("报单信息更新缓存出错", ex);
        }
    }

    /// <summary>
    /// 通过缓存读取报单数据
    /// </summary>
    private void FillFormByObjectCache()
    {
        var order = ObjectCacheHelper.GetObjectCache<OrderInfo>(CacheID.Value);

        if (order != null)
        {
            EnglishName.Text = order.EnglishCompanyName;
            ChineseName.Text = order.ChineseCompanyName;
            RegisterRegion.SelectedValue = order.RegisterRegionID.ToString();
            Stock.Text = order.RegisterStock.ToString();
            RegisterDate.Text = order.RegisiterDate.ToString("yyyy-MM-dd");

            DelegateType.SelectedValue = order.DelegateTypeID.ToString();
            Branch.SelectedValue = order.BranchID.ToString();
            Empolyee.SelectedValue = order.EmpolyeeID.ToString();
            CurrencyType.SelectedValue = order.CurrencyType.ToString();
            Amount.Text = order.Amount.ToString();
            OrderRemark.Text = order.Remark;
            CompanyID.Text = order.CompanyID;
            CheckBox1.Checked = order.IsSubsidiary;
            TextBox1.Text = order.ParentCompanyID;

            ClientName.Text = order.ClientName;
            Telephone.Text = order.Telephone;
            Mobile.Text = order.Mobile;
            Address.Text = order.Address;
            Email.Text = order.Email;
            IM.Text = order.IM;
            Fax.Text = order.Fax;

            ClientType.SelectedValue = (order.ClientType == global::ClientType.Customer ? "1" : "2");
            AgentCompany.Text = order.AgentCompanyName;


            if (order.DelegateTypeID == 5)
            {
                txtBr.Text = order.BR;
                txtBusinessAddress.Text = order.BusinessAddress;
                txtBusinessScope.Text = order.BusinessScope;
                txtEndTime.Text = order.EndTime.ToString("yyyy-MM-dd");
                txtStartTime.Text = order.StartTime.ToString("yyyy-MM-dd");
                txtTotalTurnover.Text = order.TotalTurnover.ToString();
                txtProfitTax.Text = order.ProfitTax.ToString();
                HeShuUl.Visible = true;
            }

        }
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        Label1.Visible = CheckBox1.Checked;
        TextBox1.Visible = CheckBox1.Checked;
    }

    /// <summary>
    /// 公司编号改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CompanyID_TextChanged(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(CompanyID.Text.Trim()))
        {
            return;
        }

        if (CompanyID.Text.Trim().Equals("待录入") || CompanyID.Text.Trim().Equals("非公司"))
        {
            return;
        }

        // 如果为分行，不进行数据提取
        if (CheckBox1.Checked)
        {
            return;
        }

        // 如果公司编号的长度大于5
        if (CompanyID.Text.Trim().Length > 5)
        {
            var company = new CompanyBLL().GetCompanyInfoByCompanyIDAndRegionID(CompanyID.Text.Trim(), RegisterRegion.SelectedValue);

            // 公司信息不为空
            if (company != null)
            {
                if (DelegateType.SelectedValue != "47")
                {
                    EnglishName.Text = company.EnglishName;
                    ChineseName.Text = company.ChineseName;
                }
                RegisterRegion.SelectedValue = company.RegisterRegionID.ToString();
                Stock.Text = company.Stock.ToString();
                RegisterDate.Text = company.RegisterDate.ToString("yyyy-MM-dd");
            }
        }
    }

    protected void DelegateType_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (DelegateType.SelectedValue)
        {
            // 如果为注册，则不需要输入公司编号
            case "3":
                CompanyID.Text = "待录入";
                CompanyID.Enabled = false;
                SPANYearAudit.Visible = false;
                HeShuUl.Visible = false;
                break;

            // 如果为找单或者为丢单，则不输入成交价
            case "34":
            case "52":
                Amount.Text = "0";
                Amount.Enabled = false;
                HeShuUl.Visible = false;
                break;

            // 如果为年检，则显示年检年
            case "4":
                SPANYearAudit.Visible = true;
                HeShuUl.Visible = false;
                break;

            case "5":
                HeShuUl.Visible = true;
                Amount.Enabled = true;
                CompanyID.Enabled = true;
                SPANYearAudit.Visible = false;
                break;

            default:
                Amount.Enabled = true;
                CompanyID.Enabled = true;
                SPANYearAudit.Visible = false;
                HeShuUl.Visible = false;
                break;
        }


    }

    /// <summary>
    /// 客户类型改变时的事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ClientType_SelectIndexChanged(object sender, EventArgs e)
    {
        // 只有中介才显示中介公司名称
        if (ClientType.SelectedValue == "2")
        {
            AgentName.Visible = true;
            AgentCompany.Visible = true;
        }
        else
        {
            AgentName.Visible = false;
            AgentCompany.Visible = false;
        }
    }

    /// <summary>
    /// 绑定年检的最长期限
    /// </summary>
    private void BindYearAuditList()
    {
        AuditYear.Items.Clear();

        int year = DateTime.Now.Year;

        for (int i = year; i < year + 3; i++)
        {
            ListItem item = new ListItem();
            item.Value = i.ToString();
            item.Text = i + "年";

            AuditYear.Items.Add(item);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (DelegateType.SelectedValue == "3"
            && RegisterRegion.SelectedValue == "1"
                && !CheckBox1.Checked)
        {
            //AlertMsg("需要审核，但该功能并未完成。");
            var v = new HKCompanyBLL().ChackCompanyName(EnglishName.Text, ChineseName.Text);

            labCompanyName.Text = "";

            if (v["en"].Count > 0)
            {
                labCompanyName.Text += "英文名：<br />";
                foreach (var com in v["en"])
                {
                    labCompanyName.Text += string.Format("{0}({1},{2})<br />", com.CompanyName, com.CompanyID, com.ActiveStatus);
                }

                AlertMsg("请注意，英文名有重复");
            }



            if (v["ch"].Count > 0)
            {
                labCompanyName.Text += "中文名：<br />";
                foreach (var com in v["ch"])
                {
                    labCompanyName.Text += string.Format("{0}({1},{2})<br />", com.CompanyName, com.CompanyID, com.ActiveStatus);
                }
                AlertMsg("请注意，中文名有重复");
            }

        }
        else
        {
            AlertMsg("无需审核");
        }
    }
}